package controlSoftware.util;

import java.io.File;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DeviceListXMLParser {
	final static String xmlDir = "xml/";
	final static String deviceListSchema = xmlDir + "deviceListSchema.xsd";
	String deviceListXML = xmlDir + "deviceList.xml";
	int numOfEntries = 0;

	public DeviceListXMLParser() {
	}

	public DeviceListXMLParser(String deviceListXML) {
		this.deviceListXML = deviceListXML;
	}

	public void spawnUserThreads() throws Exception {
		SchemaFactory factory = SchemaFactory
				.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		Schema schema = factory.newSchema(new File(deviceListSchema));
		Validator validator = schema.newValidator();

		File xmlFile = new File(deviceListXML);
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder dBuilder = builderFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(xmlFile);
		
        validator.validate(new DOMSource(doc));
		doc.getDocumentElement().normalize();
		
		NodeList deviceList = doc.getElementsByTagName("device");
		NodeList recordList = doc.getElementsByTagName("record");
		numOfEntries = deviceList.getLength() + recordList.getLength();
		//test
		System.out.print("number: " + numOfEntries);
		
		//retrieve device info, spawn threads accordingly and add thread to userPool
		for(int i = 0; i < deviceList.getLength(); i++){

		}
		
		//retrieve record info, spawn threads accordingly and add thread to userPool
		for(int i = 0; i < recordList.getLength(); i++){
			
		}
		

	}

	public int getNumOfEntries() {
		return numOfEntries;
	}	
}
